package faw.car.ccentersdk.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.text.TextUtils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.Objects;

public class FileUtils {
    private static final String TAG = "FileUtils";

    public static void fileCopy(String fileName, String srcPath, String destPath) {
        try {
            // 确保目标目录存在
            Files.createDirectories(Paths.get(destPath));

            // 目标文件路径
            String destFilePath = destPath + "/" + fileName;

            // 复制文件
            Files.copy(Paths.get(srcPath), Paths.get(destFilePath), StandardCopyOption.REPLACE_EXISTING);

            HQCarLog.i(TAG, "文件复制成功!");
        } catch (IOException e) {
            HQCarLog.e(TAG, "文件复制失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static String checkXmlFileExist(Context context, String filePathName) {
        File file = new File(context.getFilesDir() + "/conf/", filePathName);
        if (file.exists() && file.length() > 0) {
            HQCarLog.d(TAG, file.toPath() + " already exist!");
            return file.toPath().toString();
        }
        HQCarLog.w(TAG, file.toPath() + " NOT exist!");
        return "";
    }

    public static String copyXmlFileFromAssetsAndSave(Context context, String assetsFileName) throws IOException {
        return copyXmlFileFromAssetsAndSave(context, assetsFileName, null);
    }

    //将assets文件夹中的XML文件复制并保存到应用的内部存储中
    public static String copyXmlFileFromAssetsAndSave(Context context, String assetsFileName, String saveFileName) throws IOException {
        AssetManager assetManager = context.getAssets();
        InputStream inputStream = assetManager.open(assetsFileName);

        if (TextUtils.isEmpty(saveFileName)) {
            HQCarLog.d(TAG, "saveFileName is Empty! use assetsFileName by default!");
            saveFileName = assetsFileName;
        }
        //File file = new File(saveFileName);//普通应用无法直接访问’/data‘目录,需要申请权限.
        //fileDir指应用内部存储（如：/data/user/10/com.example.fastddsserver/files ）
        File file = new File(context.getFilesDir() + "/conf/", saveFileName);

        Files.createDirectories(file.toPath().getParent()); //创建父目录
        OutputStream outputStream = Files.newOutputStream(file.toPath(), StandardOpenOption.CREATE);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, read);
        }
        inputStream.close();
        outputStream.flush();
        outputStream.close();
        HQCarLog.i(TAG, "create file:" + file.toPath());
        return file.toPath().toString();
    }

    @Deprecated
    public static void xmlCopy(Context context) {
        try {
            // 获取文件在APK内部存储的路径
            File apkFile = new File(context.getFilesDir() + "/conf/", "wq.xml");
            // 获取要复制到的目标文件路径
            File etcFile = new File("/etc/wqNew.xml");
            // 确保目标目录存在
            if (Objects.requireNonNull(etcFile.getParentFile()).mkdirs()) {
                HQCarLog.d(TAG, "xml file already exist!");
            } else {
                HQCarLog.d(TAG, "xml file NOT exist!");
            }
            // 复制文件
            Process su = Runtime.getRuntime().exec("su");
            DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
            // 使用cat命令从APK读取文件，然后重定向到目标文件
            outputStream.writeBytes("cat " + apkFile.getAbsolutePath() + " > " + etcFile.getAbsolutePath() + "\n");
            outputStream.writeBytes("exit\n");
            outputStream.flush();
            su.waitFor();
            HQCarLog.d(TAG, "xml copy success from filePath:" + apkFile.toPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void getAppDirectoryTest(Context context) {
        HQCarLog.i(TAG, "getFilesDir(): " + context.getFilesDir().toString());
        HQCarLog.i(TAG, "getCacheDir(): " + context.getCacheDir().toString());

        // methods below will return null if the permissions denied
        HQCarLog.i(TAG, "getExternalFilesDir(Environment.DIRECTORY_MOVIES): " + context.getExternalFilesDir(Environment.DIRECTORY_MOVIES));

        HQCarLog.i(TAG, "getExternalCacheDir(): " + context.getExternalCacheDir());
        HQCarLog.i(TAG, "getRootDirectory(): " + Environment.getRootDirectory().toString());
        HQCarLog.i(TAG, "getDataDirectory(): " + Environment.getDataDirectory().toString());
        HQCarLog.i(TAG, "getDownloadCacheDirectory(): " + Environment.getDownloadCacheDirectory().toString());
        HQCarLog.i(TAG, "getExternalStorageDirectory(): " + Environment.getExternalStorageDirectory().toString());

        HQCarLog.i(TAG, "getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES): " + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString());
    }

}
